﻿/* http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/ */
angular.module("GrayParrot.AngularJS.Directives.FileUpload", []).directive('fileUpload', function ($parse) {
    return {
        scope: true,        //create a new scope
        compile: function (element, attrs, scope) {
            var modelAccessor = $parse(attrs.ngModel);

            var html = "<input type='file' id='" + attrs.id + "' class='form-control' file-upload />";

            var newElem = $(html);
            element.replaceWith(newElem);

            return function (scope, element, attrs, controller, $parse) {
                var mm = element;

                element.bind('change', function (event) {
                    var files = event.target.files;
                    //iterate files since 'multiple' may be specified on the element
                    for (var i = 0; i < files.length; i++) {
                        files[i].folder = scope.to.folder;

                        scope.$emit("fileSelected", { file: files[i] });

                        var fileProp = {};
                        for (var properties in files[i]) {
                            if (!angular.isFunction(files[i][properties])) {
                                fileProp[properties] = files[i][properties];
                            }
                        }
                        scope.fc.$setViewValue(fileProp);
                    }
                });
            };
        }
    };
});